import { defineStore } from 'pinia'
import axiosClient from '@/utils/axios'
import { useGeneralStore } from './general'

export const useMindMapStore = defineStore('mindMap', {
  state: () => ({
    mindMapGenerated: false,
    mindMapData: null,
    hasNewRecords: false,
    isLoading: false,
    pageNumbers: [],
    history: [],
    currentHistoryIndex: -1
  }),
  actions: {
    // 获取当前思维导图
    async getMindMap() {
      this.isLoading = true
      try {
        const generalStore = useGeneralStore()
        const materialId = generalStore.getMaterialId()
        
        if (!materialId) {
          console.error('材料ID未设置')
          return false
        }
        
        const response = await axiosClient.get(`/agent/mindmap?material_id=${materialId}`)
        
        if (response.data && response.data.data && response.data.data.children && response.data.data.children.length > 0) {
          this.mindMapData = response.data
          this.mindMapGenerated = true
        } else {
          this.mindMapData = null
          this.mindMapGenerated = false
        }
        
        return this.mindMapGenerated
      } catch (error) {
        console.error('获取思维导图失败:', error)
        return false
      } finally {
        this.isLoading = false
      }
    },
    
    // 检查是否有新记录
    async checkNewRecords() {
      try {
        const generalStore = useGeneralStore()
        const materialId = generalStore.getMaterialId()
        
        if (!materialId) {
          console.error('材料ID未设置')
          return false
        }
        
        const response = await axiosClient.get(`/agent/mindmap/checkNewRecords?material_id=${materialId}`)
        this.hasNewRecords = response.data.has_new_records
        this.pageNumbers = response.data.page_numbers
        return this.hasNewRecords
      } catch (error) {
        console.error('检查新记录失败:', error)
        return false
      }
    },
    
    // 生成思维导图
    async generateMindMap() {
      this.isLoading = true
      try {
        const generalStore = useGeneralStore()
        const materialId = generalStore.getMaterialId()
        
        if (!materialId) {
          console.error('材料ID未设置')
          return false
        }
        
        const response = await axiosClient.post('/agent/mindmap/generate', {
          material_id: materialId
        })
        
        this.mindMapData = response.data
        this.mindMapGenerated = true
        this.hasNewRecords = false
        
        return true
      } catch (error) {
        console.error('生成思维导图失败:', error)
        return false
      } finally {
        this.isLoading = false
      }
    },
    
    // 更新思维导图
    async updateMindMap() {
      this.isLoading = true
      try {
        const generalStore = useGeneralStore()
        const materialId = generalStore.getMaterialId()
        
        if (!materialId) {
          console.error('材料ID未设置')
          return false
        }
        
        const response = await axiosClient.post('/agent/mindmap/update', {
          material_id: materialId
        })
        
        this.mindMapData = response.data
        this.hasNewRecords = false
        
        return true
      } catch (error) {
        console.error('更新思维导图失败:', error)
        return false
      } finally {
        this.isLoading = false
      }
    },
    // 保存思维导图数据
    async saveMindMapData(data) {
      try {
        const generalStore = useGeneralStore()
        const materialId = generalStore.getMaterialId()
        if (!materialId) {
          throw new Error('未选择材料')
        }
        this.isLoading = true;
        // 调用 API 保存数据
        await axiosClient.post('/agent/mindmap/save', {
          material_id: materialId,
          mindmap_json: data
        });
        this.mindMapData = data;
        return true;
      } catch (error) {
        console.error('保存思维导图失败', error);
        throw error;
      } finally {
        this.isLoading = false;
      }
    },    
    // 新增：记录历史
    addHistory(data) {
      console.log("新增历史记录：",JSON.stringify(data))

      // 限制最大历史记录数为5
      if (this.history.length >= 5) {
        this.history.shift();
      }
      
      this.history.push(data);
    },
    
    undoLastChange() {
      if (this.history.length > 0) {
        return this.history.pop();
      } else  {
        return null; // 或者返回初始空状态
      }
    },
    // 重置历史记录的状态
    resetHistory() {
      this.history = []
      this.currentHistoryIndex = -1
    },
    
    // 重置状态
    resetState() {
      this.mindMapGenerated = false
      this.mindMapData = null
      this.hasNewRecords = false
      this.isLoading = false
      this.pageNumbers = []
      this.history = []
      this.currentHistoryIndex = -1
    }
  }
})
